﻿package meteo; // Always use packages. Never use default package.

import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;

import core.Heat;
import core.HeatDb;

/**
 * Very simplistic servlet that generates plain text. Uses the @WebServlet
 * annotation that is supported by Tomcat 7 and other servlet 3.0 containers.
 * 
 * From <a href="http://courses.coreservlets.com/Course-Materials/">the
 * coreservlets.com tutorials on servlets, JSP, Struts, JSF 2.x, Ajax, jQuery,
 * GWT, Spring, Hibernate/JPA, Hadoop, and Java programming</a>.
 */

@WebServlet("/meteo")
public class MeteoServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8355240584559713699L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String reponse = "";

		// Traiter la page d'accueil et l'affichage suivant les paramètres

		// Récupérer la page
		String page = request.getParameter("typeReq");

		// Traiter les pages
		if (page == null) {

		} else if (page.equals("home")) {

		} else if (page.equals("temperatures")) {
			reponse = affichageTemperature(request);
		} else if (page.equals("hygrometries")) {
			reponse = affichageHygrometrie(request);
		} else if (page.equals("both")) {
			reponse = affichageTout(request);
		} else if (page.equals("heat")) {
			reponse = affichageHeat(request);
		} else if (page.equals("graph")) {
			reponse = affichageGraphs();
		} else if (page.equals("weather")) {
			reponse = affichageWeather(request);
		}

		response.getWriter().print(reponse);

	}

	public String affichageTemperature(HttpServletRequest request)
			throws IOException {
		String reponse = "<script> $(function() { ";
		HeatDb.connect();
		List<String> conditions = getConditions(request);

		reponse += "var mesMarkers = []; ";
		reponse += HeatDb.getTemperatures(conditions);
		reponse += " new MarkerClusterer(map, mesMarkers, {maxZoom : 15}); ";
		reponse += "});</script>";
		// System.out.println("j'ai fini");
		// System.out.println(reponse);
		return reponse;
	}

	public String affichageHygrometrie(HttpServletRequest request)
			throws IOException {
		String reponse = "<script> $(function() { ";
		HeatDb.connect();
		List<String> conditions = getConditions(request);

		reponse += "var mesMarkers = []; ";
		reponse += HeatDb.getHygrometries(conditions);
		reponse += " new MarkerClusterer(map, mesMarkers, {maxZoom : 15}); ";
		reponse += "});</script>";
		// System.out.println("j'ai fini");
		// System.out.println(reponse);
		return reponse;
	}

	public String affichageHeat(HttpServletRequest request) throws IOException {
		String reponse = "<script> $(function() { ";
		HeatDb.connect();
		List<String> conditions = getConditions(request);

		reponse += "var heatmapData = []; ";
		reponse += HeatDb.getHeats(conditions);
		reponse += " var heatmap = new google.maps.visualization.HeatmapLayer({ "
				+ "data : heatmapData , radius: 15" + "}); " + "heatmap.setMap(map); ";
		reponse += "});</script>";
		// System.out.println("j'ai fini");
		 System.out.println(reponse);
		return reponse;
	}

	public String affichageTout(HttpServletRequest request) throws IOException {

		String reponse = "<script> $(function() { ";
		HeatDb.connect();
		List<String> conditions = getConditions(request);

		reponse += "var mesMarkers = []; ";
		reponse += HeatDb.getMixtes(conditions);
		reponse += " new MarkerClusterer(map, mesMarkers, {maxZoom : 15}); ";
		reponse += "});</script>";
		// System.out.println("j'ai fini");
		// System.out.println(reponse);
		return reponse;
	}

	public static List<String> getConditions(HttpServletRequest request) {
		List<String> result = new ArrayList<String>();

		String dateStart = request.getParameter("dateStart");
		if (dateStart != null) {
			dateStart = dateStart.replace("-", "");
			result.add("(number(replace(substring(string($mesure/@date), 1, 10), '-', '')) >= "
					+ dateStart + " )");
		}

		String dateEnd = request.getParameter("dateEnd");
		if (dateEnd != null) {
			dateEnd = dateEnd.replace("-", "");
			result.add("(number(replace(substring(string($mesure/@date), 1, 10), '-', '')) <= "
					+ dateEnd + " )");
		}

		String timeStart = request.getParameter("timeStart");
		if (timeStart != null) {
			timeStart = timeStart.replace(":", "") + "00";
			result.add("(number(replace(substring(string($mesure/@date), 12), ':', '')) >= "
					+ timeStart + " )");
		}

		String timeEnd = request.getParameter("timeEnd");
		if (timeEnd != null) {
			timeEnd = timeEnd.replace(":", "") + "00";
			result.add("(number(replace(substring(string($mesure/@date), 12), ':', '')) <= "
					+ timeEnd + " )");
		}
		
		String dateFixe = request.getParameter("dateFixe");
		if(dateFixe != null) {
			result.add("(contains(string($mesure/@date), \""+dateFixe+"\")) ");
		}

		return result;
	}
	
		public String affichageGraphDataByMonth() throws NumberFormatException, IOException {
		HeatDb.connect();
		int sept = HeatDb.getDataNbMonth("09");
		int oct = HeatDb.getDataNbMonth("10");
		int nov = HeatDb.getDataNbMonth("11");
		
		String result = "<script>$(function(){ var data = new google.visualization.DataTable(); " +
				"data.addColumn('string', 'Topping'); " +
				"data.addColumn('number', 'Slices'); " +
				"data.addRows([ " +
				"['Septembre', "+sept+"], " +
				"['Octobre', "+oct+"], " +
				"['Novembre', "+nov+"] " +
				"]); " +
				"var options = {'title':'Le nombre d\\'enregistrement par mois', " +
				"'width':400, " +
				"'height':300}; " +
				"chart.draw(data, options); " +
				"});</script>";
		return result;
	}
	
	public String affichageGraphAVHTempByMonth() throws NumberFormatException, IOException {
		HeatDb.connect();
		int sept = HeatDb.getAVGTempMonth("09");
		int oct = HeatDb.getAVGTempMonth("10");
		int nov = HeatDb.getAVGTempMonth("11");
		 
		String result = "<script>$(function(){ var data2 = new google.visualization.arrayToDataTable([" +
		                                   				"[ 'Mois', 'Température', 'Hydrométrie'], " +
		                                   				"[ 'Septembre', "+sept+", 660], "+
		                                   				"[ 'Octobre', "+oct+", 1170], " +
		                                   				"[ 'Novembre', "+nov+", 1030] ]); " +
		                                   				"var options2 = {"+
		    		                                   			"title : 'Company Performance',"+
		    		                                   			"hAxis : {"+
		    		                                   				"title : 'Year',"+
		    		                                   				"titleTextStyle : {"+
		    		                                   					"color : 'red'"+
		    		                                   				"}"+
		    		                                   			"}"+
		    		                                   		"};" +
				"chart2.draw(data2, options2); " +
				"});</script>";
		return result;
		                                   		
	}
	
	public String affichageGraphs()throws NumberFormatException, IOException {
		HeatDb.connect();
		double sept = HeatDb.getdatagraph("09", 0);
		double oct = HeatDb.getdatagraph("10", 0);
		double nov = HeatDb.getdatagraph("11", 0);
		double septA = HeatDb.getdatagraph("09", 1);
		double octA = HeatDb.getdatagraph("10", 1);
		double novA = HeatDb.getdatagraph("11", 1);
		double septB = HeatDb.getdatagraph("09", 2);
		double octB = HeatDb.getdatagraph("09", 2);
		double novB = HeatDb.getdatagraph("09", 2);
		double inu = HeatDb.getdatagraph("09", 3);
		int tot = HeatDb.getNbData();
		double uti = tot-inu;
		String result = "<script>$(function(){ var data = new google.visualization.DataTable(); " +
				"data.addColumn('string', 'Topping'); " +
				"data.addColumn('number', 'Slices'); " +
				"data.addRows([ " +
				"['Septembre', "+sept+"], " +
				"['Octobre', "+oct+"], " +
				"['Novembre', "+nov+"] " +
				"]); " +
				"var options = {'title':'Pourcentage des enregistrements par mois', " +
				"'width':400, " +
				"'height':300}; " +
				"chart.draw(data, options); " +
				" var data2 = new google.visualization.arrayToDataTable([" +
   				"[ 'Mois', 'Temperature', 'Hydrometrie'], " 	 +
   				"[ 'Septembre', "+septA+", "+septB+"], "+
   				"[ 'Octobre', "+octA+", "+septB+"], " +
   				"[ 'Novembre', "+novA+", "+septB+"] ]); " +
   				"var options2 = {"+
               			"title : 'Temperature et hygrometrie moyenne par mois',"+
               			"legend: 'bottom',"+
               			"width : 560, "+
               			"height : 300, "+
               			"hAxis : {"+
               				"title : '',"+
               				"titleTextStyle : {"+
               					"color : 'red'"+
               				"}"+
               			"}"+
               		"};" +
"chart2.draw(data2, options2); " +
"var data3 = new google.visualization.DataTable(); " +
    				"data3.addColumn('string', 'Topping'); " +
    				"data3.addColumn('number', 'Slices'); " +
    				"data3.addRows([ " +
    				"['Inutilisable', "+inu+"], " +
    				"['Utilisable', "+uti+"], " +
    				"]); " +
    				"var options3 = {'title':'Pourcentage de donnees inutilisables', " +
    				"'width':960, " +
    				"'height':300}; " +
    				"chart3.draw(data3, options3); "+
"});</script>";
		
		return result;
	}
	
	public String affichageWeather(HttpServletRequest request)
			throws IOException {
		String reponse = "<script> $(function() { ";
		HeatDb.connect();
		List<String> conditions = getConditions(request);

		reponse += "var mesMarkers = []; ";
		reponse += HeatDb.getWeather(conditions, request.getParameter("dateFixe"));
		reponse += " new MarkerClusterer(map, mesMarkers, {maxZoom : 15}); ";
		reponse += "});</script>";
		// System.out.println("j'ai fini");
		// System.out.println(reponse);
		return reponse;
	}
}
